<template>
  <wave-flex-box direction="column">
    <wave-flex-box height="50px" justify-content="space-between">
      <el-input
          placeholder="请输入文章标题"
          v-model="post.title"
          style="height: 100%"/>
      <el-space :size="20" style="padding: 0 20px">
        <el-button round type="primary" @click="savePost">保存</el-button>
        <user-avatar-dropdown/>
      </el-space>
    </wave-flex-box>
    <MdEditor style="height: 90vh" flex="1" @onUploadImg="onUploadImg" v-model="post.content"/>

  </wave-flex-box>

  <el-dialog v-model="closePageModel"
             append-to-body
             title="Warning" width="500">
    <el-result
        icon="success"
        title="Success Tip"
        sub-title="Please follow the instructions">
      <template #extra>
        <el-button @click="closePage" type="primary">关闭页面</el-button>
      </template>
    </el-result>
  </el-dialog>
</template>

<script setup>
import {ref} from 'vue';
import {MdEditor} from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import WaveFlexBox from "@/component/WaveFlexBox.vue";
import UserAvatarDropdown from "@/views/component/UserAvatarDropdown.vue";
import {useUserStore} from "@/store/index.js";
import {postSave} from "@/views/system/post/js/PostRequest.js";
import {fileUploadSingle} from "@/views/system/fileUpload/js/FileUploadRequest.js";
import {ElMessage} from "element-plus";
import Func from "@/utils/Utils.js";

const userStore = useUserStore();
const post = ref({
  authorId: '',
  title: '',
  content: '',
})

const closePageModel = ref(false);
const savePost = () => {
  post.value.authorId = userStore.userInfo.id
  if (Func.isAnyEmpty(post.value)){
    ElMessage.warning('缺少必填内容')
    return
  }
  postSave(post.value).then(res => {
    if (res.success) {
      ElMessage.success('保存成功')
      closePageModel.value = true;
    }
  })
}


const onUploadImg = async (files, callback) => {
  try {
    const uploadPromises = files.map(async (file) => {
      const response = await fileUploadSingle(file, userStore.userInfo.id);
      return response.data;
    });

    const results = await Promise.all(uploadPromises);
    console.log(results, 'results');
    const urls = results.map(item => item.url);
    console.log('上传成功，URL列表:', urls);
    callback(urls);

  } catch (error) {
    console.error('上传失败:', error);
    callback([]);
  }
};

const closePage = () => {
  window.close()
}

</script>